<template>
  <div class="word-editor-container mx-auto p-4 max-w-6xl">
    <!-- 标题区域 -->
    <header class="mb-6">
      <h1 class="text-2xl font-bold text-gray-800 mb-2 flex items-center">
        <i class="fa fa-file-word-o text-primary mr-2"></i>Word 文档编辑器
      </h1>
      <p class="text-gray-600">上传 Word 文档(.docx)，自动解析并导入到富文本编辑器中</p>
    </header>

    <!-- 文件上传区域 -->
    <div class="mb-6 p-6 bg-white rounded-xl shadow-md">
      <h2 class="text-xl font-semibold text-gray-800 mb-4">上传 Word 文档</h2>
      
      <div 
        ref="dropArea"
        class="drop-area border-2 border-dashed border-gray-300 rounded-lg p-8 text-center transition-all duration-300"
      >
        <input 
          ref="fileInput"
          type="file" 
          accept=".docx" 
          class="hidden"
          @change="handleFileSelection"
        >
        
        <div class="flex flex-col items-center justify-center">
          <i class="fa fa-cloud-upload text-4xl text-gray-400 mb-4"></i>
          <p class="text-gray-600 mb-2">拖放 Word 文档到此处，或</p>
          <button 
            @click="selectFile" 
            class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 flex items-center"
          >
            <i class="fa fa-file-text-o mr-2"></i>选择文档
          </button>
          <p class="text-sm text-gray-500 mt-4">支持的格式：.docx</p>
        </div>
        
        <!-- 上传进度条 -->
        <div 
          v-if="isProcessing" 
          class="mt-4 w-full bg-gray-200 rounded-full h-2.5"
        >
          <div 
            class="bg-primary h-2.5 rounded-full transition-all duration-300" 
            :style="{ width: progress + '%' }"
          ></div>
        </div>
      </div>
      
      <!-- 文档信息 -->
      <div 
        v-if="selectedFile" 
        class="mt-4 p-4 bg-gray-50 rounded-lg"
      >
        <div class="flex items-center">
          <i class="fa fa-file-word-o text-primary text-2xl mr-3"></i>
          <div>
            <p class="font-medium text-gray-800">{{ selectedFile.name }}</p>
            <p class="text-sm text-gray-600">{{ formatFileSize(selectedFile.size) }}</p>
          </div>
          <button 
            @click="removeFile" 
            class="ml-auto text-gray-500 hover:text-danger transition-colors"
          >
            <i class="fa fa-times-circle"></i>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 处理状态 -->
    <div 
      v-if="status.message" 
      class="mb-6"
    >
      <div 
        :class="[
          'py-3 px-4 rounded-lg flex items-center',
          status.type === 'info' ? 'bg-blue-50' : 
          status.type === 'success' ? 'bg-green-50' : 
          status.type === 'warning' ? 'bg-yellow-50' : 'bg-red-50'
        ]"
      >
        <i 
          :class="[
            'mr-3 text-xl',
            status.type === 'info' ? 'fa-info-circle text-blue-600' : 
            status.type === 'success' ? 'fa-check-circle text-green-600' : 
            status.type === 'warning' ? 'fa-exclamation-triangle text-yellow-600' : 'fa-times-circle text-red-600'
          ]"
        ></i>
        <span>{{ status.message }}</span>
      </div>
    </div>
    
    <!-- TinyMCE 编辑器 -->
    <div class="mb-6 p-6 bg-white rounded-xl shadow-md">
      <h2 class="text-xl font-semibold text-gray-800 mb-4">富文本编辑器</h2>
      <div ref="editorContainer" class="editor-container border border-gray-300 rounded-lg overflow-hidden"></div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="flex flex-wrap gap-4 p-6 bg-white rounded-xl shadow-md">
      <button 
        @click="parseDocument" 
        :disabled="!selectedFile || isProcessing" 
        class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 flex items-center disabled:opacity-50 disabled:cursor-not-allowed"
      >
        <i class="fa fa-magic mr-2"></i>解析文档
      </button>
      <button 
        @click="clearEditor" 
        class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium py-2 px-6 rounded-lg transition-all duration-300 flex items-center"
      >
        <i class="fa fa-trash-o mr-2"></i>清空编辑器
      </button>
      <button 
        @click="saveContent" 
        class="bg-accent hover:bg-accent/90 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 flex items-center ml-auto"
      >
        <i class="fa fa-save mr-2"></i>保存内容
      </button>
    </div>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce';
import 'tinymce/themes/silver/theme';
import 'tinymce/icons/default/icons';
import 'tinymce/plugins/advlist';
import 'tinymce/plugins/autolink';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/link';
import 'tinymce/plugins/image';
import 'tinymce/plugins/charmap';
import 'tinymce/plugins/preview';
import 'tinymce/plugins/anchor';
import 'tinymce/plugins/searchreplace';
import 'tinymce/plugins/visualblocks';
import 'tinymce/plugins/code';
import 'tinymce/plugins/fullscreen';
import 'tinymce/plugins/insertdatetime';
import 'tinymce/plugins/media';
import 'tinymce/plugins/table';
import 'tinymce/plugins/help';
import 'tinymce/plugins/wordcount';
import mammoth from 'mammoth/mammoth.browser';
// import { saveAs } from 'file-saver';
import '@fortawesome/fontawesome-free/css/all.min.css';

import 'tinymce/plugins/paste';
import 'tinymce/skins/ui/oxide/skin.min.css';
import 'tinymce/skins/content/default/content.min.css';

export default {
  name: 'TinymceEditor2',
  data() {
    return {
      selectedFile: null,
      editor: null,
      isProcessing: false,
      progress: 0,
      status: {
        type: 'info',
        message: '请上传 Word 文档(.docx)'
      }
    };
  },
  mounted() {
    this.initEditor();
    this.setupDragAndDrop();
  },
  beforeDestroy() {
    this.destroyEditor();
  },
  methods: {
    // 初始化TinyMCE编辑器
    initEditor() {
      tinymce.init({
        target: this.$refs.editorContainer,
        height: 400,
        menubar: true,
        plugins: [
          'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
          'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
          'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount'
        ],
        toolbar: 'undo redo | blocks | bold italic backcolor | ' +
          'alignleft aligncenter alignright alignjustify | ' +
          'bullist numlist outdent indent | removeformat | help',
        content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:16px }',
        setup: (editor) => {
          this.editor = editor;
        },
      });
    },
    
    // 销毁编辑器
    destroyEditor() {
      if (this.editor) {
        this.editor.remove();
        this.editor = null;
      }
    },
    
    // 设置拖放功能
    setupDragAndDrop() {
      const dropArea = this.$refs.dropArea;
      
      ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, this.preventDefaults, false);
      });
      
      ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, this.highlight, false);
      });
      
      ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, this.unhighlight, false);
      });
      
      dropArea.addEventListener('drop', this.handleDrop, false);
    },
    
    // 阻止默认事件
    preventDefaults(e) {
      e.preventDefault();
      e.stopPropagation();
    },
    
    // 高亮拖放区域
    highlight() {
      this.$refs.dropArea.classList.add('border-primary', 'bg-blue-50');
    },
    
    // 取消高亮拖放区域
    unhighlight() {
      this.$refs.dropArea.classList.remove('border-primary', 'bg-blue-50');
    },
    
    // 处理拖放文件
    handleDrop(e) {
      const dt = e.dataTransfer;
      const file = dt.files[0];
      
      if (file) {
        this.handleFileSelection({ target: { files: [file] } });
      }
    },
    
    // 选择文件
    selectFile() {
      this.$refs.fileInput.click();
    },
    
    // 处理文件选择
    handleFileSelection(event) {
      const file = event.target.files[0];
      
      if (!file) return;
      
      if (file.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
        this.showStatus('error', '请上传 .docx 格式的 Word 文档');
        return;
      }
      
      this.selectedFile = file;
      this.showStatus('success', '文件已准备好解析');
    },
    
    // 移除文件
    removeFile() {
      this.selectedFile = null;
      this.$refs.fileInput.value = '';
      this.showStatus('info', '已移除文件');
    },
    
    // 解析文档
    async parseDocument() {
      if (!this.selectedFile || this.isProcessing) return;
      
      this.isProcessing = true;
      this.progress = 30;
      this.showStatus('info', '正在解析文档...');
      
      try {
        // 读取文件内容
        const reader = new FileReader();
        
        reader.onload = async (event) => {
          try {
            this.progress = 60;
            
            // 使用Mammoth.js解析Word文档
            const result = await mammoth.convertToHtml({ arrayBuffer: event.target.result });
            
            this.progress = 90;
            
            if (result.messages && result.messages.length > 0) {
              console.log('转换消息:', result.messages);
            }
            
            if (result.value) {
              // 将解析结果设置到TinyMCE编辑器中
              this.editor.setContent(result.value);
              this.showStatus('success', '文档解析成功！内容已导入编辑器');
            } else {
              this.showStatus('error', '文档解析失败，未获取到内容');
            }
          } catch (error) {
            console.error('解析错误:', error);
            this.showStatus('error', '文档解析过程中发生错误');
          } finally {
            this.isProcessing = false;
            this.progress = 100;
          }
        };
        
        reader.onerror = () => {
          this.showStatus('error', '文件读取失败');
          this.isProcessing = false;
          this.progress = 100;
        };
        
        reader.readAsArrayBuffer(this.selectedFile);
      } catch (error) {
        this.showStatus('error', '发生未知错误: ' + error.message);
        console.error('解析过程中发生错误:', error);
        this.isProcessing = false;
        this.progress = 100;
      }
    },
    
    // 清空编辑器
    clearEditor() {
      if (confirm('确定要清空编辑器内容吗？')) {
        this.editor.setContent('');
        this.showStatus('info', '编辑器内容已清空');
      }
    },
    
    // 保存内容
    saveContent() {
      const content = this.editor.getContent();
      
      if (!content.trim()) {
        this.showStatus('warning', '编辑器内容为空，无需保存');
        return;
      }
      
      // 这里可以添加保存内容的逻辑，例如发送到服务器
      this.showStatus('success', '内容已保存！');
      
      // 模拟保存操作
      setTimeout(() => {
        this.showStatus('info', '准备就绪，可以继续编辑或上传新文档');
      }, 2000);
    },
    
    // 显示状态消息
    showStatus(type, message) {
      this.status = { type, message };
      
      // 3秒后自动清除错误和警告状态
      if (type === 'error' || type === 'warning') {
        setTimeout(() => {
          if (this.status.type === type) {
            this.status = { type: 'info', message: '请上传 Word 文档(.docx)' };
          }
        }, 3000);
      }
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
  }
};
</script>

<style scoped>
.word-editor-container {
  font-family: 'Inter', system-ui, sans-serif;
}

.drop-area {
  transition: all 0.3s ease;
}

.editor-container {
  min-height: 400px;
}

button {
  transition: all 0.3s ease;
}

table {
    border-collapse: collapse;
}
td, th {
    border: 1px solid black;
    padding: 8px;
}
</style>